import { createRouter, createWebHashHistory } from 'vue-router'
import { useStore } from 'vuex'
import store from '@/store'
import { h, render } from 'vue'

// 路由懒加载，按需引入
const Layout = () => import('@/views/Layout')
const HomePage = () => import('@/views/home/index')
// 一级路由组件与二级路由组件的注册  与home同为二级路由
const Categorylist = () => import('@/views/category/index')
const sub = () => import('@/views/category/sub')
const Goods = () => import('@/views/goods/index')
const Login = () => import('@/views/login/index')
const callBack = () => import('@/views/login/callBack')
const XtxCartPage = () => import('@/views/cart/index')
const goCheckedOut = () => import('@/views/member/pay/checkedOut')
const PayPage = () => import('@/views/member/pay/index')
const callBackPage = () => import('@/views/member/pay/callback')
const MemberLayout = () => import('@/views/member/Layout')
const MemberHome = () => import('@/views/member/home')
const MemberOrder = () => import('@/views/member/order') 
const MyDetail = () => import('@/views/member/order/detail')
const routes = [
  // 一级路由布局容器
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/', component: HomePage },
      // 二级路由注册
      { path: '/category/:id', component: Categorylist },
      { path: '/category/sub/:id', component: sub },
      { path: '/product/:id', component: Goods },
      { path: '/cart', component: XtxCartPage },
      { path: '/member/checked', component: goCheckedOut },
      { path: '/member/pay', component: PayPage },
      { path: '/pay/callback', component: callBackPage },
      {
        path: '/member',
        component: MemberLayout,
        children: [
          { path: '/member', component: MemberHome },
          { path: '/member/order/', component:{render:() => h(<RouterView/>)},children:[
            { path:'',component:MemberOrder },
            { path:':id',component:MyDetail }
          ]},
          
        ]
      }
    ]
  },
  {
    path: '/login',
    component: Login,
  },
  {
    path: '/login/callBack',
    component: callBack
  }
]
// vue3创建路由实例
const router = createRouter({
  // 使用hash的路由实例
  history: createWebHashHistory(),
  routes,
  // 滚动到页面顶部
  scrollBehavior() {
    return { left: 0, top: 0 }
  }
})
// const store = useStore()
// 前置路由守卫  在支付之前进行拦截
router.beforeEach((to, from, next) => {
  const { profile } = store.state.user
  if (to.path.startsWith('/member' && !profile.token)) {
    return next('/login?redirectUrl=' + to.fullPath)
  }
  next()
})
export default router
